import java.io.IOException;
import java.net.*; 

/**
* class Main: main entry of maze program
*   - parse command line args for retrieve various parameters, such like local/remove server, maze size, treasure number and play name
*   - initialize and start local server with maze size, treasure number
*   - initialize client with server IP, local host IP and player name 
*/

public class Main {

	static int m_MazeSize ;
	static int m_NrOfTreasures;	
	static String m_PlayerName;
	static String m_RemoteServerIP; // 
	static String m_ServerIP;
	static String m_ClientIP; 
	
	static void PrintHelpInfo() {
		System.out.println("Request arguments: <p1> <p2> <p3> <p4> ");
		System.out.println("\t p1: 1 - sserver,  0 - client ");
		System.out.println("\t(for server) ");
		System.out.println("\t\tp2: maze size ");
		System.out.println("\t\tp3: treasure number ");
		System.out.println("\t\tp4: Player name ");
		System.out.println("\t(for client) ");
		System.out.println("\t\tp2: default server IP ");
		System.out.println("\t\tp3: player name ");
	}
	
	static void PrintArgErrorInfo()  {
		System.out.println("arguments error!");
		System.exit(1);
	}
		
	/**
	 * @param 1 N M playerName (server)
	 * 		  0 IP  playerName (client)
	 *   - see Help Info
	 */
	public static void main(String[] args) throws IOException  {

		InetAddress thisIp;
		String m_isSrv;

		// get local host and IP	
		try {
			thisIp = InetAddress.getLocalHost();
			m_ClientIP = thisIp.getHostAddress();
		}
		catch(Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
		
		// parse command line args
		if (args.length == 0)
		{
			PrintHelpInfo();
			System.exit(1);
		}
		else 
		{	
			m_isSrv = args[0];
		    if(m_isSrv.equals("1"))   // local server
			{ 
				if (args.length == 4)
				{
					m_MazeSize = Integer.parseInt(args[1]);
					m_NrOfTreasures = Integer.parseInt(args[2]);
					m_PlayerName = args[3];
				}
				else
				{
					PrintArgErrorInfo();					
				}
				
				// initiate local server with maze size and treaure number
				// server is running in thread, see Class Server
				new Server(m_MazeSize, m_NrOfTreasures, true).start(); 
				m_ServerIP = m_ClientIP; 
			}
			else if(m_isSrv.equals("0")) // remote server
			{ 
				if (args.length == 3)
				{
					m_RemoteServerIP = args[1];
					m_PlayerName = args[2];
				}
				else
				{
					PrintArgErrorInfo();					
				}
				
				//  remote server
				m_ServerIP = m_RemoteServerIP ;
			}
			else
			{
				PrintArgErrorInfo();
				System.exit(1);
			}
		}	
		
		System.out.println("Server IP: " + m_ServerIP);
		
		new Client (m_ServerIP, m_ClientIP,  m_PlayerName );	
		
	}
}
